package zhongbo.javaweb.instagram.web.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import zhongbo.javaweb.instagram.dto.JsonRespDto;
import zhongbo.javaweb.instagram.model.BaseModel;
import zhongbo.javaweb.instagram.service.model.BaseService;

import java.util.List;

/**
 * 说明：
 *
 * @author zhongboWork
 * @version 1.0
 * @since 2021-12-21 16:19
 */
public abstract class BaseController<MODEL extends BaseModel> {

    @Autowired
    protected BaseService<MODEL> baseService;

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "添加一条记录接口")
    public JsonRespDto<MODEL> addOne(@RequestBody MODEL entity) {
        return edit(entity);
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "删除一条记录接口")
    public JsonRespDto<MODEL> delete(@PathVariable("id") String id) {
        MODEL delete = baseService.delete(id);
        if (delete == null) {
            return new JsonRespDto<MODEL>().makeError().appendMsg("删除失败");
        }
        return new JsonRespDto<MODEL>().makeSuccess().setData(delete);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改记录接口")
    public JsonRespDto<MODEL> edit(@RequestBody MODEL edit) {
        MODEL addOrUpdate = baseService.addOrUpdate(edit);
        if (addOrUpdate == null) {
            return new JsonRespDto<MODEL>().makeError().appendMsg("修改失败");
        }
        return new JsonRespDto<MODEL>().makeSuccess().setData(addOrUpdate);
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询记录接口")
    public JsonRespDto<MODEL> findOne(@PathVariable("id") String id) {
        MODEL one = baseService.findOne(id);
        return new JsonRespDto<MODEL>().makeSuccess().setData(one);
    }

    @ResponseBody
    @RequestMapping(value = "/findAll", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询所有记录接口")
    public JsonRespDto<List<MODEL>> find() {
        List<MODEL> modelList = baseService.findAll();
        return new JsonRespDto<List<MODEL>>().makeSuccess().setData(modelList);
    }

}
